using System;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace Super
{
	public static class MethodCore
	{
		/// <summary>
		/// 挂载脚本并且保存预制体
		/// </summary>
		/// <param name="addr">脚本路径</param>
		/// <param name="name">生成对象名称</param>
		public static void HangScriptSavePrefab(string addr, string name)
		{
#if UNITY_EDITOR
			MonoScript scriptAsset = AssetDatabase.LoadAssetAtPath<MonoScript>(addr);
			GameObject GO = GameObject.Find(name);
			if (GO == null) return;

			Type scriptType = scriptAsset.GetClass();
			Component component = GO.AddComponent(scriptType);
			MethodInfo methodInfo = scriptType.GetMethod("OnDirtyRefresh");
			methodInfo.Invoke(component, null);
			
			bool isPanel = name.Contains("Panel");
			string path = isPanel ? PathSettingSO.Ins.panelPrefabPath : PathSettingSO.Ins.widgetPrefabPath;
			path = string.Format(path, name);

			string directory = GlobalUtil.GetAbsolutePath(Path.GetDirectoryName(path));
			if (!Directory.Exists(directory))
			{
				Directory.CreateDirectory(directory);
			}

			//UserAction：存在同名文件时，弹窗提示处理。AutomatedAction：unity默认处理，生成唯一的路径
			//PrefabUtility.SaveAsPrefabAsset生成的预制体和GO没有联系
			GameObject prefabs = PrefabUtility.SaveAsPrefabAssetAndConnect(GO, path, InteractionMode.UserAction);
			AssetDatabase.Refresh();

			AssetUtil.CreateOrMoveEntry(ValueSettingSO.Ins.prefabAGroup, path);
#endif
		}
		
		public static void LoadExcelData(string excelPath)
		{
			ExcelUtil.LoadExcel(excelPath);
		}
		
		public static void LoadAllExcel()
		{
			#if UNITY_EDITOR
			ExcelUtil.LoadAllExcel();
			#endif
		}

	}

}
